package com.leyou.user.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.auth.mapper.DetailMapper;
import com.leyou.auth.mapper.GoodsMapper;
import com.leyou.auth.mapper.SkuMapper;
import com.leyou.auth.mapper.SpuMapper;
import com.leyou.search.pojo.*;
import com.leyou.service.IBrandService;
import com.leyou.service.IcategoryService;
import com.leyou.service.IgoodsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import rx.internal.util.unsafe.MpmcArrayQueue;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.leyou.common.constants.MQConstants.Exchange.ITEM_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKey.ITEM_DOWN_KEY;
import static com.leyou.common.constants.MQConstants.RoutingKey.ITEM_UP_KEY;

@Service
public class goodsServiceImpl implements IgoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private IBrandService brandService;

    @Autowired
    private IcategoryService categoryService;

    @Autowired
    private DetailMapper detailMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    @Transactional
    public PageResult<SpuDTO> querySpuByPage(Integer page, Integer rows, Boolean saleable, String key) {
        PageHelper.startPage(page, rows);

        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(key)
        ) {
            criteria.orLike("name", "%" + key + "%");
        }

        if (saleable != null) {
            criteria.orEqualTo("saleable", saleable);
        }
        example.setOrderByClause("update_time DESC");

        List<Spu> list = goodsMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }

        List<SpuDTO> spuDTOS = BeanHelper.copyWithCollection(list, SpuDTO.class);

        spuDTOS.forEach(spuDTO -> {
            BrandDTO brandDTO = brandService.queryById(spuDTO.getBrandId());
            spuDTO.setBrandName(brandDTO.getName());
            String categoryName = categoryService.queryCategoryByIds(spuDTO.getCategoryIds()).stream().map(CategoryDTO::getName).collect(Collectors.joining("/"));
            spuDTO.setCategoryName(categoryName);
        });

        PageInfo<Spu> pageInfo = new PageInfo<>(list);

        return new PageResult<SpuDTO>(pageInfo.getTotal(), spuDTOS);
    }

    @Override
    @Transactional
    public void saveGoods(SpuDTO spuDTO) {
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        int count = goodsMapper.updateByPrimaryKey(spu);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        SpuDetailDTO spuDetail1DTO = spuDTO.getSpuDetail();
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDetail1DTO, SpuDetail.class);
        spuDetail.setSpuId(spu.getId());
        count = detailMapper.updateByPrimaryKeySelective(spuDetail);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        List<SkuDTO> skus = spuDTO.getSkus();
        ArrayList<Sku> skuList = new ArrayList<>();
        skus.forEach(skuDTO -> {
            skuDTO.setSpuId(spu.getId());
            Sku sku = BeanHelper.copyProperties(skuDTO, Sku.class);
            skuList.add(sku);
        });
        count = skuMapper.insertList(skuList);
        if (count != skuList.size()) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }


    @Override
    @Transactional
    public void updateSpuSaleable(Long id, Boolean saleable) {
        Spu spu = new Spu();
        spu.setId(id);
        spu.setSaleable(saleable);
        int count = goodsMapper.updateByPrimaryKeySelective(spu);
        if (count != 1) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        Sku sku = new Sku();
        sku.setEnable(saleable);
        Example example = new Example(Sku.class);
        example.createCriteria().andEqualTo("spuId", id);
        count = skuMapper.updateByExampleSelective(sku, example);

        int size = skuMapper.selectCountByExample(example);
        if (count != size) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
        // 发送mq消息
        String key = saleable ? ITEM_UP_KEY : ITEM_DOWN_KEY;
        amqpTemplate.convertAndSend(ITEM_EXCHANGE_NAME, key, id);
    }

    @Override
    public SpuDetailDTO querySpuDetailById(Long spuId) {
        SpuDetail spuDetail = detailMapper.selectByPrimaryKey(spuId);
        if (spuDetail == null) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyProperties(spuDetail, SpuDetailDTO.class);
    }

    @Override
    public List<SkuDTO> querySkuBySpuId(Long spuId) {
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        List<Sku> skus = skuMapper.select(sku);
        return BeanHelper.copyWithCollection(skus, SkuDTO.class);
    }

    @Override
    public void UpdateGoods(SpuDTO spuDTO) {
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        int count = goodsMapper.updateByPrimaryKeySelective(spu);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        SpuDetailDTO spuDetail1DTO = spuDTO.getSpuDetail();
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDetail1DTO, SpuDetail.class);
        count = detailMapper.updateByPrimaryKeySelective(spuDetail);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        Sku sku = new Sku();
        sku.setSpuId(spu.getId());
        int size = skuMapper.selectCount(sku);
        if (size > 0) {
            count = skuMapper.delete(sku);
            if (count != size) {
                throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
            }

        }

        List<SkuDTO> skuDTOList = spuDTO.getSkus();
        ArrayList<Sku> skuList = new ArrayList<>();
        skuDTOList.forEach(skuDTO -> {
            skuDTO.setSpuId(spu.getId());
            Sku sku1 = BeanHelper.copyProperties(skuDTO, Sku.class);
            skuList.add(sku1);
        });
        count = skuMapper.insertList(skuList);
        if (count != skuList.size()) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    @Override
    public SpuDTO querySpuById(Long id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        SpuDTO spuDTO = BeanHelper.copyProperties(spu, SpuDTO.class);

        spuDTO.setSkus(querySkuBySpuId(id));

        spuDTO.setSpuDetail(querySpuDetailById(id));
        return spuDTO;
    }

    @Override
    public List<SkuDTO> querySkuByIds(List<Long> ids) {
        List<Sku> skus = skuMapper.selectByIdList(ids);
        if (CollectionUtils.isEmpty(skus)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(skus, SkuDTO.class);
    }

    @Override
    @Transactional
    public void minusStock(Map<Long, Integer> map) {
        map.entrySet().forEach(cart -> {
            Long skuId = cart.getKey();
            Integer num = cart.getValue();
            Sku sku = skuMapper.selectByPrimaryKey(skuId);
            int storeNum = sku.getStock() - num;

            if (storeNum < 0) {
                //库存不足
                throw new LyException(ExceptionEnum.STOCK_NOT_ENOUGH);
            }

            sku.setStock(storeNum);
            int count = skuMapper.updateByPrimaryKey(sku);
            if (1 != count) {
                throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
            }
        });
    }

    @Override
    public void plusStock(Map<Long, Integer> map) {
        map.entrySet().forEach(cart -> {
            Long skuId = cart.getKey();
            Integer num = cart.getValue();
            Sku sku = skuMapper.selectByPrimaryKey(skuId);
            int storeNum = sku.getStock() + num;

            sku.setStock(storeNum);
            int count = skuMapper.updateByPrimaryKey(sku);
            if (1 != count) {
                throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
            }
        });
    }
}